--
-- Author: yawei.zhu
-- Date: 2018-06-22 15:50:11
--
local AvatarFactory = require("app.public.avatar.AvatarFactory")
local PvpChampionFormPagePanel = import(".PvpChampionFormPagePanel")
local PvpChampionFormRender = import(".renders.PvpChampionFormRender")

local PvpChampionForm = class("PvpChampionForm")

function PvpChampionForm:ctor(node)
	self._formNode = node
	
	self:initNode()
end

function PvpChampionForm:initNode()
	local formPanel = self._formNode:getChildByName("Panel")
	local titleTxt = formPanel:findChild("Panel_tlt/tlt")
	titleTxt:setString( L("champion_notice5") )
	self._bottomTxt = formPanel:findChild("Panel_bom_text/Text")

	-- 决赛
	self._finalPanel = formPanel:getChildByName("Panel_final")
	local finalTxt = self._finalPanel:getChildByName("tlt")
	finalTxt:setString(L("champion_desc1"))
	self._teamName1 = self._finalPanel:getChildByName("name_1")
	self._teamName2 = self._finalPanel:getChildByName("name_2")
	for i = 1, 6 do
		local head = self._finalPanel:getChildByName("head_"..i)
		head:getChildByName("Panel"):setTouchEnabled(false)
		head:findChild("Panel/bg_foe"):setVisible(false)
		head:findChild("Panel/bg_team"):setVisible(false)
		if i <= 3 then
			head:findChild("Panel/bg_team"):setVisible(true)
		else
			head:findChild("Panel/bg_foe"):setVisible(true)
		end

		self["_icon"..i] = head:findChild("Panel/icon_img")
	end

	local bg1 = self._finalPanel:getChildByName("bg1")
	bg1:setTouchEnabled(true)
	bg1:addClickEventListener(function()
		executeFunc(self._onOperate, "showTeamDetailInfo", self._finalTeams[1].teamId)
	end)
	local bg2 = self._finalPanel:getChildByName("bg2")
	bg2:setTouchEnabled(true)
	bg2:addClickEventListener(function()
		executeFunc(self._onOperate, "showTeamDetailInfo", self._finalTeams[2].teamId)
	end)

	-- bom
	self._btnEnter = formPanel:findChild("Panel_bom/Button_enter")
	self._btnEnter:addClickEventListener(function()  
		executeFunc(self._onOperate, "PvpChampion_EnterMatch")
	end)
	local buttonNode = formPanel:findChild("Panel_bom/Button_tips")
	buttonNode:getChildByName("Panel_1"):addClickEventListener(function()
		executeFunc(self._onOperate, "PvpChampion_search_4", self._throneDay)
	end)

	-- Panel_form
	self._formPanel = formPanel:getChildByName("Panel_form")
	self._leftBtn = self._formPanel:getChildByName("btn_1")
	self._rightBtn = self._formPanel:getChildByName("btn_2")
	self._pageTitle = self._formPanel:getChildByName("tlt")
	local dotPanel = self._formPanel:getChildByName("Panel_dot")
	self._dots = {}
	for i = 1, 9 do
		self._dots[i] = dotPanel:getChildByName("dot_"..i)
	end

	local function pageViewEvent(sender, evt)
        if evt == ccui.PageViewEventType.turning then
            local pageIndex = sender:getCurPageIndex()
            if self._curPage == pageIndex then return end
            self._curPage = pageIndex
            self:switchPage()
        end
    end

	self._pageView = self._formPanel:findChild("PageView")
	self._pageView:setCustomScrollThreshold(1/3 * self._pageView:getContentSize().width)
    self._pageView:addEventListener(pageViewEvent)
    self._pageSize = self._pageView:getContentSize()

    for i = 1, 8 do
    	local page = self:loadPage()
		self._pageView:addPage(page)
    end
    self._curPage = 0

    self._leftBtn:addClickEventListener(function()
		self._pageView:scrollToPage(self._curPage - 1)
	end)
    self._rightBtn:addClickEventListener(function()
		self._pageView:scrollToPage(self._curPage + 1)
	end)

	-- 冠军比分
	self._championPlay = formPanel:findChild("Panel_bom/Panel_play")
	self._championPlay:getChildByName("img_play"):setVisible(false)
end

function PvpChampionForm:loadPage()
	local layout = ccui.Layout:create()
	local panel = PvpChampionFormPagePanel.create()
	panel:setTag(100)
	panel:setPosition(cc.p(0, 0))
	panel:onOperate(function(op, data)
		executeFunc(self._onOperate, op, data)
	end)
	layout:addChild(panel)
	layout:setContentSize(panel:getChildByName("Panel"):getContentSize())
	return layout
end

-- maxPage = 8 或 9 
function PvpChampionForm:setMaxPageCount(maxPage)
	if maxPage ~= 8 and maxPage ~= 9 then return end
	self._maxPageCount = maxPage
	self:initPageDot()

	if self._maxPageCount == 8 then
		self._pageView:removePageAtIndex(8) -- 把第9页删掉，下标是从0开始的
		if self._curPage == 8 then 
			self._curPage = 0
			self._pageView:scrollToPage(0)
		end
	else
		local page = self._pageView:getPage(8)
		if not page then
			self._pageView:addPage(self:loadPage())
		end
	end
	self:switchPage()
end

function PvpChampionForm:switchPage()
	display.setBtnTouchEnable(self._leftBtn, self._curPage > 0)
	display.setBtnTouchEnable(self._rightBtn, self._curPage < (self._maxPageCount - 1))

	self:selectPageDot(self._curPage + 1)
end

function PvpChampionForm:updateInfo(finalTeamInfo, myTeamIsKickOut, myTeamId, rank)
	-- 未报名
	if not finalTeamInfo then
		self:setMaxPageCount(8)
		for i = 1, 8 do
			local panel = self._pageView:getPage(i - 1):getChildByTag(100)
			panel:setData({{}, -1})
		end

		self._btnEnter:setVisible(false)
		self._bottomTxt:setString(L("champion_desc2"))
		return
	end

	self._myTeamId = myTeamId

	self._formPanel:setVisible(false)
	self._finalPanel:setVisible(false)

	-- 判断是否为决赛（有且只有两个的队伍round为5）
	self._finalTeams = finalTeamInfo:getFinalWarTeams()
	if self._finalTeams then
		self._finalPanel:setVisible(true)
		self:updateFinalTeams(self._finalTeams)
	else
		self._formPanel:setVisible(true)
		local teams = finalTeamInfo:getTeamInfos()
		local battleResults = finalTeamInfo:getBattleResults()	
		self:updateFormView(teams, battleResults)
		-- 1、跳转到最强赛区 2、跳转到我的队伍所在的区
	end

	-- 按钮显示
	if app:sendMsg("NewActivityDungeonsModel", "isChampionMap") then 
		self._btnEnter:setVisible(false)
	else
		if myTeamIsKickOut then
			self._btnEnter:setVisible(false)
		else
			self._btnEnter:setVisible(true)
		end
	end	

	-- 为参赛时的提示
	local function getDesc()
		local weekDay = tonumber(app.session:getServerWeekDate())
		if weekDay == 0 then weekDay = 7 end

		-- 判断是否在本周开服
		local openDay = app.session:getOpenServerDays()
		if openDay <= weekDay then
			return L("champion_desc2") -- 你未参赛
		end

		if weekDay >= 1 and weekDay <= 5 then
			return L("champion_desc2") -- 你未参赛
		elseif weekDay == 6 then
			return L("champion_desc13") -- 周二、周四的64强具有参赛资格
		else
			return L("champion_desc14") -- 周一、周三、周五的64强具有参赛资格
		end
	end

	-- 文字显示
	local szDesc = ""
	if myTeamId <= 0 then 
		szDesc = getDesc()

	else
		local teamInfo = finalTeamInfo:getTeamInfoById(myTeamId)
		if not teamInfo then
			-- szDesc = L("throne_out64")
			szDesc = string.format(L("throne_ownerout64"), rank) -- 你队的排名为%d，未进入64强淘汰赛
		else
			if myTeamIsKickOut then -- 被淘汰
				if teamInfo.round == 0 then
					szDesc = L("throne_loseIn32")
				elseif teamInfo.round == 1 then
					szDesc = L("throne_loseIn16")
				elseif teamInfo.round == 2 then 
					szDesc = L("champion_desc4")
				elseif teamInfo.round == 3 then
					szDesc = L("champion_desc5")
				elseif teamInfo.round == 4 then
					szDesc = L("champion_desc6")
				elseif teamInfo.round == 5 then
					szDesc = L("champion_desc7")
				end
			else
				if teamInfo.round == 0 then
					-- szDesc = L("throne_winIn64")
					szDesc = string.format(L("throne_ownerin64"), rank) -- 你队的排名为%d，成功进入64强淘汰赛
				elseif teamInfo.round == 1 then
					szDesc = L("throne_winIn32")
				elseif teamInfo.round == 2 then
					szDesc = L("champion_desc8")
				elseif teamInfo.round == 3 then 
					szDesc = L("champion_desc9")
				elseif teamInfo.round == 4 then
					szDesc = L("champion_desc10")
				elseif teamInfo.round == 5 then
					szDesc = L("champion_desc11")
				else
					szDesc = L("champion_desc12")
					self._btnEnter:setVisible(false)
				end	
			end
		end
	end

	self._bottomTxt:setString(szDesc)
end

function PvpChampionForm:updateFormView(teams, battleResults)
	self._teamInfos = {}

	dump(teams)

	local myTeamPage = 0
	local bShow = false -- 是否显示最强赛区
	local lastTeams = {} -- 最终赛区的数据
	for iPage = 1, 8 do
		local arrTeams = {}
		local round = 0
		for i = 1, 8 do
			local index = i + (iPage - 1) * 8
			local teamInfo = teams[index]
			arrTeams[i] = teamInfo
			-- 该区是否已经决出冠军
			if teamInfo.round >= 3 then 
				local value = {}
				value.part = teamInfo.part
				value.idx = teamInfo.Idx
				value.teamName = teamInfo.teamName
				value.round = teamInfo.round - 3
				value.teamId = teamInfo.teamId
				lastTeams[iPage] = value
				bShow = true
			end
			-- 是否有我自己的队伍
			if self._myTeamId > 0 and teamInfo.teamId == self._myTeamId then
				myTeamPage = iPage - 1
			end
		end

		local page = self._pageView:getPage(iPage - 1)
		local panel = page:getChildByTag(100)
		panel:setData({arrTeams, self._myTeamId, battleResults})
	end

	if bShow then
		self:setMaxPageCount(9)
		local panel = self._pageView:getPage(8):getChildByTag(100)
		panel:setData({lastTeams, self._myTeamId, battleResults, true})
		self._pageView:scrollToPage(8)
	else
		self:setMaxPageCount(8)
		self._pageView:scrollToPage(myTeamPage)
	end

	-- 获取battleResult
	local function getBattleResult(teamInfo1, teamInfo2)
		if not battleResults then return end
		if not teamInfo1 or not teamInfo2 then return end
		local teamId1 = teamInfo1.teamId
		local teamId2 = teamInfo2.teamId
		if not teamId1 or not teamId2 then return end

		for _, data in ipairs(battleResults) do
			if (data.TeamA == teamId1 and data.TeamB == teamId2) or (data.TeamA == teamId2 and data.TeamB == teamId1) then
				return data
			end
		end
	end

	-- 如果已经决出冠军，则显示决赛的比分
	local finalTeams = {}
	for _, team in ipairs(teams) do
		if team.round >= 5 then
			table.insert(finalTeams, team)
		end
	end
	if #finalTeams == 2 and (finalTeams[1].round >= 6 or finalTeams[2].round >= 6) then -- 已经产生了冠军
		local teamL = finalTeams[1]
		local teamR = finalTeams[2]
		if finalTeams[1].part ~= 0 then -- part 取值0或1
			teamL = finalTeams[2]
			teamR = finalTeams[1]
		end
		local battleResult = getBattleResult(teamL, teamR)
		if battleResult then
			local finalPanel = self._championPlay
			finalPanel:setVisible(true)
			self._bottomTxt:setVisible(false)

			local scoreL = battleResult.ScoreA
			local scoreR = battleResult.ScoreB
			if teamL.teamId == battleResult.TeamB then
				scoreL = battleResult.ScoreB
				scoreR = battleResult.ScoreA
			end
			if teamR.teamId == battleResult.WonTeam then
				finalPanel:getChildByName("bg"):setScaleX(-1)
			end
			-- 设置队伍名称 和 比分
			finalPanel:getChildByName("name_1"):setString(teamL.teamName)
			finalPanel:getChildByName("name_2"):setString(teamR.teamName)
			finalPanel:getChildByName("num_1"):setString(scoreL)
			finalPanel:getChildByName("num_2"):setString(scoreR)
		end
	end
end

function PvpChampionForm:updateFinalTeams(teams)
	self._teamName1:setString(teams[1].teamName)
	self._teamName2:setString(teams[2].teamName)


	for i = 1, 6 do
		self["_icon"..i]:setVisible(false)
	end
	-- 拉取左边队伍的信息
	executeFunc(self._onOperate, "reqThroneTeamById", {teamId = teams[1].teamId, cb = function(throneTeam)
		if not throneTeam then return end
		for i = 1, 3 do 
			self:setIcon(throneTeam:getUserBaseInfo(i), i)
		end
	end})
	-- 拉取右边队伍的信息
	executeFunc(self._onOperate, "reqThroneTeamById", {teamId = teams[2]. teamId, cb = function(throneTeam)
		if not throneTeam then return end
		for i = 1, 3 do 
			self:setIcon(throneTeam:getUserBaseInfo(i), i + 3)
		end
	end})
end

-- 显示其他天对战信息
function PvpChampionForm:updateOtherDayTeams(teams, day, battleResults)
	self._formNode:findChild("Panel/Panel_bom_text"):setVisible(false)
	self._formNode:findChild("Panel/Panel_final"):setVisible(false)
	-- self._formNode:findChild("Panel/Panel_bom"):setVisible(true)
	self._formNode:findChild("Panel/Panel_bom/Button_enter"):setVisible(false)
	self._throneDay = day

	self._myTeamId = -1

	if teams and #teams == 64 then
		-- 是否有自己的队伍
		for _, team in ipairs(teams) do
			local throneTeam = team.throneTeam
			for i = 1, 3 do
				local member = throneTeam:getUserBaseInfo(i)
				if member and member.uid == UD:getUid() then
					self._myTeamId = team.teamId
					break
				end
			end
			if self._myTeamId ~= -1 then break end
		end

		self:updateFormView(teams, battleResults)
	else
		self:setMaxPageCount(8)
		for i = 1, 8 do
			local panel = self._pageView:getPage(i - 1):getChildByTag(100)
			panel:setData({{}, -1})
		end

		self._bottomTxt:setString(L("champion_notice3"))
		return
	end
end

function PvpChampionForm:setIcon(params, index)
	if not params then return end
	AvatarFactory.getOrCreateHeroIconPath(params,function(path)
        if not tolua.isnull(self._formNode) then
            self["_icon"..index]:loadTexture(path)
            self["_icon"..index]:setVisible(true)
        end
    end)
end

function PvpChampionForm:getTeamInfo(idx)
	return self._teamInfos[idx]
end

function PvpChampionForm:setShow(visible)
	self._formNode:setVisible(visible)
end

function PvpChampionForm:initPageDot()
	local midX = 60
	local intervalX = 14.4
	local midNum = (self._maxPageCount + 1) / 2
	for i = 1, 9 do
		local dot = self._dots[i]
		if i <= self._maxPageCount then 
			dot:setVisible(true)
			dot:setPositionX(midX - (midNum - i) * intervalX)
		else
			dot:setVisible(false)
		end
	end
end

function PvpChampionForm:selectPageDot(index)
	for i = 1, 9 do
		local dot = self._dots[i]
		if i == index then
			dot:setColor(cc.c3b(0xFF, 0xEB, 0xB8))
		else
			dot:setColor(cc.c3b(0x70, 0x5C, 0x3A))
		end
	end

	if index == 9 then
		self._pageTitle:setString(L("throne_finalArea"))
	else
		self._pageTitle:setString(string.format(L("throne_Area"), index))
	end
end

function PvpChampionForm:onOperate(cb)
	self._onOperate = cb
end


return PvpChampionForm

